<?php

require_once '../bootstrap.php';
require_once '../../../LIBS/DES.class.php';
require_once '../models/Configs.php';
require_once '../models/Skeys.php';
require_once '../models/Lkeys.php';
require_once '../models/Users.php';

use LIBS\DES;
use app\models\Configs;
use app\models\Skeys;
use app\models\Lkeys;
use app\models\Users;

$appkey = $_GET['appkey'];
$data = $_GET['data'];

$row = Configs::getConfigByAppkey($appkey);
$secret = $row['secret'];

$des = new DES($secret);
$data_decrypt = $des->decrypt($data);

if ( $data_decrypt )
{
    $arr = explode(';', $data_decrypt);
    $skey = $arr[0];

    $row = Skeys::getSkeys($appkey, $skey);
    if ( $row )
    {
        # skey 失效
        Skeys::delSkey($appkey, $skey);

        $user_id  = $row['user_id'];
        $row = Users::getUserById($user_id);
        if ( $row )
        {
            $arr = [
                'user_id'   => $user_id,
                'appkey'    => $appkey,
                'name'      => $row['name'],
                'type'      => $row['type'],
                'expired_at'=> time() + 7200,
                'lkey'      => uniqid(md5(time()).'_'),
                'ret_time'  => time()
            ];

            # insert lkey
            Lkeys::saveLkey($arr);

            echo json_encode([
                "code" => 0,
                "data" => [
                    "name"      => $arr['name'],
                    "type"      => $arr['type'],
                    "expired_at"=> $arr['expired_at'],
                    "lkey"      => $arr['lkey'],
                    "ret_time"  => $arr['ret_time']
                ]
            ]);
            exit;
        }
    }
}

echo json_encode([
    'code' => -1,
    'data' => []
]);

?>
